/**
 *
 *
 *
 let res = await requestGet('/login',{parmas:'aaa'}) // 失败了就失败了

 let res1 = await reduceRequest(requestGet,{parmas:'aaa'}) // 失败了 会再次请求 设置次数 1000 每次请求的时间间隔500

 */
/**
 *
 * @param request  上层应用的请求api
 * @param params   上层应用需要的参数
 * @param attemptTimes 失败重连的次数
 * @param interval 重连的时间间隔
 * @returns {Promise<any>}
 */
function reduceRequest(request, params, attemptTimes = 10000, interval = 500) {
  // attemptTimes = attemptTimes ? attemptTimes && attemptTimes >= 1 : 10000;
  // interval = interval ? interval && interval >= 100 : 500;
  if (attemptTimes <= 0 || interval <= 100) {
    throw new Error('attemptTimes and interval must be a ingeter');
  }
  return new Promise((resolve, reject) => {
    // 不断地执行request
    // 直到成功或者次数达到上限为止
    function executePromise(timer) {
      //1. 判断次数
      if (attemptTimes < 1) {
        // 1.1 清除定时器
        clearInterval(timer);
        // 1.2 调用reject
        reject(new Error('promise not until timeout'));
        // 1.3 return
        return void 0;
      }
      attemptTimes -= 1;
      //2. 等待成功 resolve
      let {url, args} = params;
      return request(url, args).then(res => {
        clearInterval(timer);
        resolve(res);
      }).catch(e => {
        throw new Error(e);
      })

      // request().then().catch()
    }

    let timer = setInterval(() => {
      executePromise(timer);
    }, interval);
    executePromise(timer);
  });

}
